import { Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {NgbModal} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-course',
  templateUrl: './course.component.html',
  styleUrls: ['./course.component.scss']
})
export class CourseComponent implements OnInit {
  // 课程列表
  public courseList: any;
  public search = {
    courseName: '',
  };
  // 弹框标题 1.新增课程，2.修改课程
  courseType = 1;
  courseForm = new FormGroup({
    course_name: new FormControl('', [
      Validators.required,
      Validators.minLength(1)
    ]),
    id: new FormControl('', [
      Validators.required,
      Validators.minLength(1)
    ]),
  })
  constructor(private http: HttpClient, private modalService: NgbModal) { }
  ngOnInit(): void {
    this.initData();
  }
  /*
  * 初始化请求
  * */
  initData(): void {
    const param = {
      courseName: this.search.courseName
    };
    this.http.post('/api/selectCourse', param, {headers: {'Content-Type': 'application/json'}})
      .subscribe(res => {
        this.courseList = res || [];
      });
  }
  /*
  * 条件查询
  * */
  search_course(): void {
    this.initData();
  }
  /*
  * 修改新增模态框
  * */
  showCourseModel(type: number, content: any, data: any): void{
    this.courseType = type;
    if (this.courseType === 2){
      this.courseForm.patchValue({
        course_name: data.course_name,
        id: data.id,
      });
    } else{
      this.courseForm.patchValue({
        course_name: '',
        id: '',
      });
    }
    this.modalService.open(content, {size: 'lg', ariaLabelledBy: 'modal-basic-title'});
  }
  /*
  * delCourse
  * */
  delCourse(data: any): void{
    const {id} = data;
    const $confirm = window.confirm('确定要删除当前课程吗？');
    if ($confirm){
      this.http.post('/api/deleteCourse', {id}, {headers: {'Content-Type': 'application/json'}})
        .subscribe((res: any) => {
          this.initData();
          window.alert('删除成功');
        });
    }
  }
}
